<template>
  <div v-loading="loading" class="addExpense">
    <el-form ref="form" :model="form" :rules="roleCodeRule" label-width="120px">
      <el-row>
        <mainTilte title="基本信息" />
      </el-row>
      <el-row>
        <el-col v-if="isEdit" :span="8">
          <el-form-item label="系统sku" prop="code">
            <el-input v-model.trim="form.code" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="中文名称" prop="name_ch">
            <el-input v-model.trim="form.name_ch" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="英文名称" prop="name_en">
            <el-input v-model="form.name_en" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="商品分类" prop="category_id">
            <product-category v-model="form.category_id" check-strictly @change="handleChangeClassify" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="所属供应商" prop="supplier_id">
            <el-autocomplete v-model="form.supplier_name" :fetch-suggestions="querySupplier" @select="handleSelect" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="采购员" prop="purchase_id">
            <app-select v-model="form.purchase_id" url="/shops/buyers" :params="purchaseParams" options-label="username" options-value="user_id" placeholder="请选择采购员" @change="changePurchaseHandler" />
          </el-form-item>
        </el-col>
        <el-col v-if="!form.purchase_price_usd" :span="8">
          <el-form-item label="采购价(RMB)" prop="purchase_price_rmb">
            <el-input-number v-model.trim="form.purchase_price_rmb" :controls="false" :min="0" :max="999999999" :precision="2" class="wfull tal" />
          </el-form-item>
        </el-col>
        <el-col v-if="!form.purchase_price_rmb" :span="8">
          <el-form-item label="采购价(USD)" prop="purchase_price_usd">
            <el-input-number v-model.trim="form.purchase_price_usd" :controls="false" :min="0" :max="999999999" :precision="2" class="wfull tal" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="商品主图" prop="image_url">
            <upload-file accept-type="image/jpeg,image/png" list-type="picture-card" :file-list="imageList" :upload-limit="1" @handleImageSuccess="handleImageSuccess" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <mainTilte title="产品信息" />
      </el-row>
      <el-row>
        <el-col :span="8">
          <el-form-item label="尺寸" prop="size">
            <el-input v-model="form.size" type="textarea" autosize />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="重量" prop="weight">
            <el-input v-model="form.weight" type="textarea" autosize />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="颜色" prop="color">
            <el-input v-model="form.color" type="textarea" autosize />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="材质" prop="material">
            <el-input v-model="form.material" type="textarea" autosize />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="计量单位" prop="unit">
            <el-select v-model.trim="form.unit" clearable placeholder="计量单位">
              <el-option v-for="(item, index) of unitList" :key="index" :label="item.dict_data_name" :value="`${item.id}`" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="箱率" prop="box_rate">
            <el-input v-model.trim="form.box_rate" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="包装方式" prop="packing_method">
            <el-select v-model.trim="form.packing_method" clearable placeholder="包装方式">
              <el-option v-for="(item, index) of splitOrderList" :key="index" :label="item.name" :value="item.code" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="其他备注" prop="other_remark">
            <el-input v-model="form.other_remark" type="textarea" autosize />
          </el-form-item>
        </el-col>
      </el-row>
      <div class="dialog-footer-center">
        <span>
          <el-button type="primary" :loading="btnLoading" @click="onSubmit">保存</el-button>
          <el-button @click="$router.go(-1)">取消</el-button>
        </span>
      </div>
    </el-form>
  </div>
</template>

<script>
import { validPrice, isNumberThanZero, validChinese, validateFirstUpperCase } from '@/utils/validate'
export default {
  data() {
    return {
      isEdit: false,
      loading: false,
      form: {
        id: '', // id
        name_ch: '', // 中文名称
        name_en: '', // 英文名称
        category_id: '', // 商品分类
        supplier_id: 0, // 供应商id
        supplier_name: '', // 供应商名称
        purchase_id: '', // 采购员
        purchase_name: '', // 采购员 name
        purchase_price_rmb: '', // 采购价格 rmb
        purchase_price_usd: '', // 采购价格 usd
        image_url: '',

        size: '', // 尺寸
        weight: '', // 重量
        color: '', // 颜色
        material: '', // 材质
        unit: '', // 计量单位
        box_rate: '', // 箱率
        packing_method: '', // 包装方式
        other_remark: '' // 其他备注
      },
      imageList: [], // 图片列表
      roleCodeRule: {
        // 中文名称
        name_ch: [
          { required: true, message: '请输入商品中文名称', trigger: 'blur' },
          {
            max: 50,
            message: '商品中文名称必须在50个字符以内',
            trigger: 'blur'
          }
        ],
        // 英文名称
        name_en: [
          {
            validator(rule, value, callback) {
              validChinese(value) ? callback(new Error('英文名称不能输入中文')) : callback()
            },
            trigger: 'blur'
          },
          {
            validator(rule, value, callback) {
              if (value && validateFirstUpperCase(value)) {
                callback(new Error('英文名称首字母必须大写'))
              } else {
                callback()
              }
            },
            trigger: 'blur'
          },
          {
            max: 50,
            message: '商品英文名称必须在50个字符以内',
            trigger: 'blur'
          }
        ],
        // 商品分类
        category_id: [
          { required: true, message: '请选择商品分类', trigger: 'blur' }
        ],
        // 供应商id
        supplier_name: [
          { required: true, message: '请输入商品供应商', trigger: 'blur' }
        ],
        // 采购员
        purchase_id: [
          { required: true, message: '请选择商品采购员', trigger: ['change', 'blur'] }
        ],
        // 采购价格 rmb
        purchase_price_rmb: [
          {
            required: true,
            message: '请输入商品采购价格(RMB)',
            trigger: 'blur'
          },
          {
            validator(rule, value, callback) {
              if (!validPrice(value)) {
                callback(new Error('采购价格(RMB)必须是数字且保留两位小数'))
              } else {
                callback()
              }
            },
            trigger: 'blur'
          }
        ],
        // 采购价格 usd
        purchase_price_usd: [
          {
            required: true,
            message: '请输入商品采购价格(USD)',
            trigger: 'blur'
          },
          {
            validator(rule, value, callback) {
              if (!validPrice(value)) {
                callback(new Error('采购价格(USD)必须是数字且保留两位小数'))
              } else {
                callback()
              }
            },
            trigger: 'blur'
          }
        ],
        // 尺寸
        size: [
          { max: 500, message: '商品尺寸必须在500个字符以内', trigger: 'blur' }
        ],
        // 重量
        weight: [
          { max: 500, message: '商品重量必须在500个字符以内', trigger: 'blur' }
        ],
        // 颜色
        color: [
          { max: 500, message: '商品颜色必须在500个字符以内', trigger: 'blur' }
        ],
        // 材质
        material: [
          { max: 500, message: '商品颜色必须在500个字符以内', trigger: 'blur' }
        ],
        // 箱率
        box_rate: [
          {
            validator(rule, value, callback) {
              isNumberThanZero(value)
                ? callback()
                : callback(new Error('必须是数字且大于0'))
            },
            trigger: 'blur'
          }
        ],
        // 其他备注
        other_remark: [
          {
            max: 500,
            message: '商品其他备注必须在500个字符以内',
            trigger: 'blur'
          }
        ]
      },
      freightList: [],
      fileList: [],
      classifyList: [],
      supplierList: [], // 供应商列表
      // 计量单位
      unitList: [],
      // 包装方式 ：1-普通商品 2-多箱包装
      splitOrderList: [
        {
          code: 1,
          name: '普通商品'
        },
        {
          code: 2,
          name: '多箱包装'
        }
      ],
      btnLoading: false,
      time: null,

      purchaseParams: {
        status: 1
      }
    }
  },
  mounted() {
    this.getSuppierList() // 获取供应商
    this.getUnitList() // 获取 计算单位
    const id = this.$route.query.id
    if (id) {
      this.editList(id)
    }
  },
  methods: {
    handleImageSuccess({ name, url }) {
      console.log('上传成功-----------------')
      console.log(`{ name: ${name}, url: ${url} }`)
      const vm = this
      vm.imageList.push({ name, url })
      vm.form.image_url = url
    },
    // 选择 采购员 处理函数
    changePurchaseHandler(e) {
      this.form.purchase_name = e.username
    },
    handleSelect(e) {
      const that = this
      that.supplier_id = e.id
    },
    // 查询 供应商
    querySupplier(queryString, cb) {
      const result = this.supplierList.filter(e => e.name.includes(queryString))
      clearTimeout(this.time)
      this.time = setTimeout(() => {
        cb(result)
      }, 1000)
    },
    // 获取 计算单位
    getUnitList() {
      const vm = this
      vm.$cache.getDic('unit').then(res => {
        vm.unitList = res
      })
    },
    // 设置 图片 列表
    setImageList(url) {
      const vm = this
      const name = url.split('/').pop()
      vm.imageList = [{ name, url }]
    },
    editList(id) {
      this.isEdit = true
      this.loading = true
      this.$http
        .get(`/product/${id}`)
        .then((res) => {
          if (res.code === 10000) {
            this.form.id = res.data.id
            this.form.code = res.data.code
            this.form.name_ch = res.data.name_ch
            this.form.name_en = res.data.name_en
            this.form.category_id = res.data.category_id
            this.form.supplier_id = res.data.supplier_id
            this.form.supplier_name = res.data.supplier_name
            this.form.purchase_id = res.data.purchase_id
            this.form.purchase_name = res.data.purchase_name
            this.form.purchase_price_rmb = +res.data.purchase_price_rmb
            this.form.purchase_price_usd = +res.data.purchase_price_usd
            if (res.data.otherData) {
              this.form.size = res.data.otherData.size // 尺寸
              this.form.weight = res.data.otherData.weight // 重量
              this.form.color = res.data.otherData.color // 颜色
              this.form.material = res.data.otherData.material // 材质
              this.form.other_remark = res.data.otherData.other_remark // 其他备注
            }
            if (res.data.packData) {
              this.form.unit = res.data.packData.unit // 计量单位
              this.form.box_rate = res.data.packData.box_rate // 箱率
            }
            this.form.packing_method = res.data.packing_method // 包装方式
            if (res.data.image_url) {
              this.setImageList(res.data.image_url)
            }
          }
          this.loading = false
        })
        .catch((err) => {
          console.log(err)
          this.loading = false
        })
      // console.log(this.form,'this.form');
    },
    getSuppierList() {
      const vm = this
      const params = {
        page: 1,
        limit: 100000000,
        audit_status: 2,
        cooperation_status: 1
      }
      vm.$http.get('/supply', { params }).then((res) => {
        vm.supplierList = res.data.map(e => {
          e['value'] = e.name
          return e
        })
      })
    },
    handleSelectSuppier(data) {
      this.form.supplier_id = data.label
    },
    handleChangeClassify(category) {
      const vm = this
      vm.form.ZH_HS = category.ZH_HS
      vm.form.EN_HS = category.EN_HS
      vm.form.tax_rebate_rate = category.tax_rebate_rate
      vm.form.tax_tariff_rate = category.tax_tariff_rate
      // vm.form.ZH_HS = category.ZH_HS;
      // this.classifyList.forEach((element) => {
      //   if (element.children && element.children.length > 0) {
      //     element.children.forEach((it) => {
      //       if (it.id === this.form.category_id) {
      //         this.form.ZH_HS = it.ZH_HS
      //         this.form.EN_HS = it.EN_HS
      //         this.form.tax_rebate_rate = it.tax_rebate_rate
      //         this.form.tax_tariff_rate = it.tax_tariff_rate
      //       }
      //     })
      //   }
      // })
    },
    queryBlnoAsync(queryString, cb) {
      // this.$http
      //   .get(`/transhipment-order?bl_no=${queryString}`)
      //   .then((res) => {
      //     if (res.code === 10000 && res.data && res.data.length > 0) {
      //       let restaurants = res.data.map((item) => {
      //         return { value: item.bl_no };
      //       });
      //       this.tableData = [];
      //       this.blNoList = res.data;
      //       let results = queryString
      //         ? restaurants.filter(this.createStateFilter(queryString))
      //         : restaurants;
      //       clearTimeout(this.timeout);
      //       this.timeoutNo = setTimeout(() => {
      //         cb(results);
      //       }, 3000 * Math.random());
      //     }
      //   })
      //   .catch((err) => {
      //     console.log(err);
      //   });
    },
    createStateFilter(queryString) {
      return (state) => {
        return (
          state.value.toLowerCase().indexOf(queryString.toLowerCase()) != -1
        )
      }
    },
    onSubmit() {
      const vm = this
      vm.$refs.form.validate((valid) => {
        if (valid) {
          vm.btnLoading = true
          vm.submit()
        }
      })
    },
    // 保存
    submit() {
      const params = Object.assign({}, this.form)
      delete params.created_at
      delete params.updated_at
      if (this.isEdit) {
        // 编辑
        this.form.type = 0
        this.$http
          .put(`/products/developEdit/${this.form.id}`, params)
          .then((res) => {
            if (res.code === 10000) {
              this.$message.success('编辑成功')
              this.$router.push('/product/dataBase')
            }
            this.btnLoading = false
          })
          .catch(() => {
            this.btnLoading = false
          })
      } else {
        // 新增
        this.$http
          .post(`/products/developAdd`, params)
          .then((res) => {
            if (res.code === 10000) {
              this.$message.success('新增成功')
              this.$router.go(-1)
            }
            this.btnLoading = false
          })
          .catch(() => {
            this.btnLoading = false
          })
      }
    }
  }
}
</script>

<style scoped>
.addExpense {
  padding: 15px;
  background: #fff;
}
/deep/.el-select,
.el-autocomplete,
.el-cascader {
  width: 100%;
}
.sizeStyle {
  display: flex;
}
.sizeStyle /deep/ .el-input__inner {
  border-right: 0;
}
.sizeStyle /deep/ .el-input-group__append {
  padding-left: 4px;
  padding-right: 4px;
  font-size: 14px;
  color: #333333;
  background: #fff;
}
</style>
